package presenter.list;

import main.InputBean;
import main.InputMode;
import utils.OnLogListener;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class FileListor {
    private final String path;
    private final boolean isDir;
    private final OnLogListener listener;
    private final StringBuilder builder = new StringBuilder();
    private final Map<Integer, String> tags = new HashMap<>();

    public FileListor(InputBean info, OnLogListener listener) {
        this.path = info.path1();
        this.isDir = info.mode() == InputMode.ListDir;
        this.listener = listener;
        log(1, String.format("文件列表：%s", path));
        init(() -> {
            start(0, path);
            createFile(listener::taskFinish);
        });

    }

    private void init(Runnable next) {
        String tag = "        ";
        for (int i = 0; i < 10; i++) {
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < i; j++) {
                builder.append(tag);
            }
            tags.put(i, builder.toString());
        }
        next.run();
    }

    private void start(int deep, String path) {
        File parent = new File(path);
        if (parent.exists() && !parent.isHidden()) {
            if (parent.isDirectory() || !isDir) {
                String name = parent.getName();
                log(deep, name);
            }
            if (parent.isDirectory()) {
                File[] items = parent.listFiles();
                if (items != null) {
                    for (File child : items) {
                        if (child.isDirectory() || !isDir) {
                            start(deep + 1, child.getAbsolutePath());
                        }
                    }
                }
            }
        }
    }

    private void createFile(Runnable next) {
        FileOutputStream fos = null;
        try {
            File root = new File(path);
            if (root.isDirectory()) {
                String name = String.format("%s文件列表.txt", root.getName());
                File log = new File(path, name);
                log.deleteOnExit();
                log.createNewFile();
                fos = new FileOutputStream(log);
                fos.write(builder.toString().getBytes());
                fos.flush();
                log(0, "文件写入成功！");
            }
        } catch (Exception ex) {
            log(0, ex.getMessage());
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception ex) {
                log(0, "fos关闭失败！");
            }
        }
        next.run();
    }

    private void log(int deep, String content) {
        String fixedContent = String.format("%s%s", tags.get(deep), content);
        builder.append(String.format("%s\r\n", fixedContent));
        listener.log(fixedContent);
    }
}
